//
//  DTHomeViewModel.swift
//  Architecture
//
//  Created by tianXin on 2017/9/14.
//  Copyright © 2017年 田鑫. All rights reserved.
//

import UIKit

class DTHomeViewModel: DTPaginationViewModel {

    public var ReturnTimeLineBlock: ReturnValueBlock! = nil
    
    func setReturnTimeLineBlock(_ TimeLineBlock:@escaping ReturnValueBlock) {
      ReturnTimeLineBlock = TimeLineBlock
    }
    
    public func detailVC(_ vc: UIViewController,didSelect model: DTHomeModel) {
      let detailVC = DTMicroblogDetailViewController()
      detailVC.model = model;
      self.PaginationVC.navigationController?.pushViewController(detailVC, animated: true)
    }

    override func loadData() {
      HomeProvider.request(.timeLine) { result in
        do {
          let response = try result.dematerialize()
          let value = try response.mapNSArray()
          guard let dataList = [DTHomeModel].deserialize(from: value) as? [DTHomeModel] else {
            return
          }
          self.ReturnTimeLineBlock(dataList)
        }
        catch {
          let printableError = error as CustomStringConvertible
          let errorMessage = printableError.description
          print(errorMessage);
        }
      }
    }
    override func requestPageData() {
      addHeadRefresh()
      PaginationVC.refreshTableView.mj_header.beginRefreshing()
    }
    override func requestPageIndex(_ pageIndex: Int,refreshType: RefreshType) {
      HomeProvider.request(.timeList(pageIndex: pageIndex,pageSize: page.pageSize)) {(result) in
        do {
          let response = try result.dematerialize()
          let value = try response.mapNSArray()
          guard let dataList = [DTHomeModel].deserialize(from: value) as? [DTHomeModel] else {
            return
          }
          self.endRefreshingWithType(refreshType: refreshType)
          self.addDataBeforeWithRefreshType(refreshType, dataArray: dataList as [Any])
          self.dataList.appendArray(scr: dataList, dest: &self.dataList)
          self.ReturnBlock(self.dataList)
        }
        catch {
          let printableError = error as CustomStringConvertible
          let errorMessage = printableError.description
          self.ErrorBlock(errorMessage)
        }
      }
    }
}
